package com.cfl.shiro;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.getRequestDispatcher("login.jsp").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String useruame = request.getParameter("userName");
		String password = request.getParameter("password");
		
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(useruame, password);
		
		try {
			subject.login(token);
			Session session = subject.getSession();
			session.setAttribute("info", "学习中shiro中");
			request.getRequestDispatcher("success.jsp").forward(request, response);
			System.out.println("身份验证成功");
		} catch (Exception e) {
			request.setAttribute("errorInfo", "用户名或密码错误");
			System.out.println("用户名或密码错误");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
	}

}
